package org.zjvis.datascience.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.security.auth.login.LoginException;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zjvis.datascience.common.model.ApiResult;
import org.zjvis.datascience.common.model.ApiResultCode;
import org.zjvis.datascience.common.vo.user.UserLoginVO;
import org.zjvis.datascience.common.vo.user.UserTokenVO;
import org.zjvis.datascience.service.LoginService;
import org.zjvis.datascience.service.PasswordService;

/**
 * @description 系统登录 Controller
 * @date 2021-12-13
 */
@Api(tags = "系统登录")
@RestController
@RequestMapping("/auth")
public class LoginController {

    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;

    @Autowired
    private PasswordService passwordService;

    @ApiOperation("登录")
    @PostMapping(value = "/login")
    public ApiResult<UserTokenVO> login(@Valid @RequestBody UserLoginVO vo) throws Exception {
        try {
            return ApiResult.valueOf(loginService.login(vo));
        }catch (LoginException e) {
            logger.warn("someone trying to hack system with incorrect pwd");
            return ApiResult.valueOf(ApiResultCode.NO_AUTH, null, e.getMessage());
        }
    }

    @ApiOperation("退出登录")
    @PostMapping(value = "/logout")
    public ApiResult logout() {
        loginService.logout();
        return new ApiResult();
    }

    @ApiOperation("获取用户信息")
    @PostMapping(value = "/info")
    public ApiResult<UserTokenVO> info() {
        return ApiResult.valueOf(loginService.getInfo());
    }

    @ApiOperation("获取公钥")
    @PostMapping(value = "/getPublicKey")
    public ApiResult<String> getPublicKey() {
        return ApiResult.valueOf(passwordService.getPublicKey());
    }

}
